<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getMajorList, getMajorPage, getCourseList, addCourseToMajor, selectByMajorId, removeCourseFromMajor, deleteMajor, addMajor } from '@/api/major.js'
import { ElPagination, ElDialog, ElTable, ElTableColumn, ElButton } from 'element-plus'

// 数据定义
const courseList = ref([])
const selectedCourse = ref(null)
const loading = ref(false)

// 模态框相关数据
const dialogVisible = ref(false)
const currentMajor = ref(null)
const dialogLoading = ref(false)

// 新增专业模态框相关数据
const addDialogVisible = ref(false)
const addDialogLoading = ref(false)
const newMajorForm = ref({
  majorName: ''
})
// 已选课程列表
const selectedCoursesList = ref([])

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchMajorName = ref('')

// 初始化数据
onMounted(() => {
  fetchData()
})

// 获取专业和课程数据
  const fetchData = async () => {
    loading.value = true
    try {
      // 获取课程列表
      const courseRes = await getCourseList()
      if (courseRes.code === 200 && courseRes.data) {
        // 确保courseId字段存在，学分字段使用credits
        courseList.value = courseRes.data.map(course => ({
          ...course,
          courseId: course.courseId || course.id
        }))
      } else {
        ElMessage.error('获取课程列表失败')
      }

      // 获取分页专业数据（用于表格显示）
      await fetchMajorPage()
    } catch (error) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }

// 分页查询专业
const fetchMajorPage = async () => {
  loading.value = true
  try {
    const pageRes = await getMajorPage(currentPage.value, pageSize.value, searchMajorName.value)
    if (pageRes.code === 200 && pageRes.data) {
      // 表格显示的数据
      majorTableData.value = pageRes.data.records || []
      total.value = pageRes.data.total || 0
    } else {
      ElMessage.error('获取专业分页数据失败')
      majorTableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取专业分页数据失败:', error)
    ElMessage.error('获取专业分页数据失败，请稍后重试')
    majorTableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchMajorPage()
}

// 处理页面大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchMajorPage()
}

// 搜索专业
const handleSearch = () => {
  currentPage.value = 1
  fetchMajorPage()
}

// 表格显示的专业数据
const majorTableData = ref([])

// 打开编辑模态框
  const openEditDialog = async (major) => {
    // 确保获取到的major对象包含majorId
    console.log('打开编辑模态框，专业信息:', major)
    
    // 可能后端返回的字段名不是majorId，这里做一下兼容处理
    currentMajor.value = {
      ...major,
      majorId: major.majorId || major.id // 兼容不同的字段名
    }
    
    const majorId = currentMajor.value.majorId
    
    dialogVisible.value = true
    
    // 重新获取最新的课程列表和已选课程
    dialogLoading.value = true
    try {
      // 并行获取所有数据
      const [courseRes, selectedRes] = await Promise.all([
        getCourseList(),
        selectByMajorId(majorId)
      ])
      
      // 处理可选课程列表
      if (courseRes.code === 200 && courseRes.data) {
        // 确保courseId字段存在，学分字段使用credits
        courseList.value = courseRes.data.map(course => ({
          ...course,
          courseId: course.courseId || course.id
        }))
        console.log('处理后的课程列表:', courseList.value)
      } else {
        ElMessage.error('获取课程列表失败')
      }
      
      // 处理已选课程列表
      if (selectedRes.code === 200 && selectedRes.data) {
        // 确保已选课程对象包含必要字段
        selectedCoursesList.value = selectedRes.data.map(course => ({
          ...course,
          courseId: course.courseId || course.id
        }))
        console.log('专业已选课程列表:', selectedCoursesList.value)
      } else {
        ElMessage.warning('获取已选课程列表失败')
        selectedCoursesList.value = []
      }
    } catch (error) {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败，请稍后重试')
      selectedCoursesList.value = []
    } finally {
      dialogLoading.value = false
    }
  }

// 添加课程到专业
  const handleAddCourseToMajor = async (courseId) => {
    if (!currentMajor.value || !courseId) {
      ElMessage.warning('参数错误')
      return
    }

    // 检查majorId是否存在且有效
    const majorId = currentMajor.value.majorId
    if (!majorId) {
      ElMessage.warning('专业ID无效')
      return
    }

    console.log('添加课程到专业:', 'majorId=' + majorId, 'courseId=' + courseId)
    
    dialogLoading.value = true
    try {
      const res = await addCourseToMajor(majorId, courseId)
      if (res.code === 200) {
        ElMessage.success(res.message || '添加课程成功')
        
        // 添加成功后刷新已选课程列表
        await refreshSelectedCourses(majorId)
      } else {
        // 直接使用后端返回的错误消息，包括"当前专业以有该课程"的提示
        ElMessage.error(res.message || '添加课程失败')
      }
    } catch (error) {
      console.error('添加课程失败:', error)
      // 显示更详细的错误信息
      if (error.isForbidden) {
        ElMessage.error('权限不足，请检查您的权限设置')
      } else {
        // 如果错误响应中有message字段，也可以尝试使用
        ElMessage.error(error.response?.data?.message || '添加课程失败，请稍后重试')
      }
    } finally {
      dialogLoading.value = false
    }
  }
  
  // 刷新已选课程列表
  const refreshSelectedCourses = async (majorId) => {
    try {
      const selectedRes = await selectByMajorId(majorId)
      if (selectedRes.code === 200 && selectedRes.data) {
        selectedCoursesList.value = selectedRes.data.map(course => ({
          ...course,
          courseId: course.courseId || course.id
        }))
        console.log('更新后的已选课程列表:', selectedCoursesList.value)
      } else {
        console.error('刷新已选课程失败:', selectedRes)
      }
    } catch (error) {
      console.error('刷新已选课程失败:', error)
    }
  }
  
  // 从专业中删除课程
  const handleRemoveCourseFromMajor = async (courseId) => {
    if (!currentMajor.value || !courseId) {
      ElMessage.warning('参数错误')
      return
    }

    // 检查majorId是否存在且有效
    const majorId = currentMajor.value.majorId
    if (!majorId) {
      ElMessage.warning('专业ID无效')
      return
    }

    console.log('从专业中删除课程:', 'majorId=' + majorId, 'courseId=' + courseId)
    
    dialogLoading.value = true
    try {
      const res = await removeCourseFromMajor(majorId, courseId)
      if (res.code === 200) {
        ElMessage.success('删除课程成功')
        
        // 删除成功后刷新已选课程列表
        await refreshSelectedCourses(majorId)
      } else {
        ElMessage.error(res.message || '删除课程失败')
      }
    } catch (error) {
      console.error('删除课程失败:', error)
      ElMessage.error(error.response?.data?.message || '删除课程失败，请稍后重试')
    } finally {
      dialogLoading.value = false
    }
  }
  
  // 删除专业
  const handleDeleteMajor = async (major) => {
    if (!major || !major.majorId && !major.id) {
      ElMessage.warning('专业信息无效')
      return
    }
    
    const majorId = major.majorId || major.id
    const majorName = major.majorName || '该专业'
    
    // 弹出确认对话框
    if (confirm(`确定要删除专业「${majorName}」吗？删除后相关数据可能无法恢复。`)) {
      loading.value = true
      try {
        const res = await deleteMajor(majorId)
        if (res.code === 200) {
          ElMessage.success('删除专业成功')
          // 刷新专业列表
          await fetchMajorPage()
        } else {
          ElMessage.error(res.message || '删除专业失败')
        }
      } catch (error) {
        console.error('删除专业失败:', error)
        ElMessage.error(error.response?.data?.message || '删除专业失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  }
  
  // 打开新增专业模态框
  const openAddDialog = () => {
    // 重置表单
    newMajorForm.value = {
      majorName: ''
    }
    addDialogVisible.value = true
  }
  
  // 处理新增专业
  const handleAddMajor = async () => {
    // 验证表单
    if (!newMajorForm.value.majorName || newMajorForm.value.majorName.trim() === '') {
      ElMessage.warning('请输入专业名称')
      return
    }
    
    addDialogLoading.value = true
    try {
      // 构建请求数据，只包含majorName字段，id和status会由后端处理
      const majorData = {
        majorName: newMajorForm.value.majorName.trim()
      }
      
      const res = await addMajor(majorData)
      if (res.code === 200) {
        ElMessage.success('新增专业成功')
        // 关闭模态框
        addDialogVisible.value = false
        // 刷新专业列表
        await fetchMajorPage()
      } else {
        ElMessage.error(res.message || '新增专业失败')
      }
    } catch (error) {
      console.error('新增专业失败:', error)
      ElMessage.error(error.response?.data?.message || '新增专业失败，请稍后重试')
    } finally {
      addDialogLoading.value = false
    }
  }
</script>

<template>
  <div class="academy-major-container">
    <h2 class="page-title">专业课程管理</h2>
    
    <el-button 
      type="primary" 
      @click="openAddDialog"
      style="margin-bottom: 20px;"
    >
      新增专业
    </el-button>
    

    <el-card class="card-container" shadow="hover" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>专业列表</span>
          <el-input
            v-model="searchMajorName"
            placeholder="搜索专业名称"
            style="width: 200px;"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>
      </template>
      
      <el-table 
        v-loading="loading" 
        :data="majorTableData" 
        style="width: 100%"
        border
      >
        <el-table-column prop="majorName" label="专业名称" width="auto" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="openEditDialog(scope.row)"
              style="margin-right: 8px;"
            >
              编辑课程
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteMajor(scope.row)"
              :loading="loading"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 编辑课程模态框 -->
      <el-dialog
        v-model="dialogVisible"
        title="编辑专业课程"
        width="90%"
      >
        <div class="modal-content">
          <!-- 左边：已选课程列表 -->
          <div class="modal-column">
            <h3 style="margin-top: 0; margin-bottom: 15px;">现有课程</h3>
            <el-table 
              v-loading="dialogLoading" 
              :data="selectedCoursesList" 
              style="width: 100%"
              border
            >
<!--              <el-table-column prop="courseId" label="课程ID" width="100" />-->
              <el-table-column prop="courseName" label="课程名称" />y
              <el-table-column prop="credits" label="学分" width="100" />
              <el-table-column prop="hours" label="学时" width="100" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="handleRemoveCourseFromMajor(scope.row.courseId || scope.row.id)"
                    :loading="dialogLoading"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 右边：可选课程列表 -->
          <div class="modal-column">
            <h3 style="margin-top: 0; margin-bottom: 15px;">添加课程</h3>
            <el-table 
              v-loading="dialogLoading" 
              :data="courseList" 
              style="width: 100%"
              border
            >
<!--              <el-table-column prop="courseId" label="课程ID" width="100" />-->
              <el-table-column prop="courseName" label="课程名称" />
              <el-table-column prop="credits" label="学分" width="100" />
              <el-table-column prop="hours" label="学时" width="100" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button 
                    type="success" 
                    size="small" 
                    @click="handleAddCourseToMajor(scope.row.courseId || scope.row.id)"
                    :loading="dialogLoading"
                  >
                    添加
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>
      
      <!-- 新增专业模态框 -->
      <el-dialog
        v-model="addDialogVisible"
        title="新增专业"
        width="500px"
      >
        <el-form
          :model="newMajorForm"
          label-width="100px"
          style="padding: 20px 0;"
        >
          <el-form-item
            label="专业名称"
            prop="majorName"
            :rules="[{ required: true, message: '请输入专业名称', trigger: 'blur' }]"
          >
            <el-input
              v-model="newMajorForm.majorName"
              placeholder="请输入专业名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddMajor" :loading="addDialogLoading">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
      
      <div class="pagination-container" style="margin-top: 20px;">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.academy-major-container {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.card-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.add-course-form {
  margin-bottom: 0;
}

/* 模态框两栏布局样式 */
.modal-content {
  display: flex;
  gap: 20px;
  height: 500px; /* 固定高度，便于滚动 */
}

.modal-column {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.modal-column .el-table {
  flex: 1;
  overflow: auto;
}

/* 确保表格在列中正确显示 */
.modal-column .el-table__body-wrapper {
  max-height: calc(100% - 40px); /* 减去标题高度 */
}
</style>